<?php
class Index extends Admin_Controller {

    public function __construct() {
        parent::__construct();

        $this->_load();
    }

    public function index() {
        
        $this->template->set_phrase_js($this->lang->language)
                        ->set_layout('default')
                        ->set_breadcrumb('Manage Product', site_url(__CLASS__))
                        ->set_breadcrumb('List product')
                        ->set_metadata(array('og:type' => 'Sell video','keywords' => 'Sell video, tuts', 'description' => 'Sell video tutorial via website'))
                        ->append_css(array(
                            'jquery.treeview',
                            'jquery.ui.datepicker',
                            'jquery.ui.autocomplete',
                            'jquery.ui.tooltip',
                            'jquery.ui.tab',
                            'admin/product'
                        ))
                        ->append_js(array(
                            'jquery.treeview',
                            'jquery.cookie',
                            'admin/menu',
                            'jquery.ui.datepicker',
                            'jquery.ui.autocomplete',
                            'jquery.ui.tooltip',
                            'jquery.ui.tab',
                            'jquery.form',
                            'tiny_mce/tiny_mce',
                            'admin/product/index'
                            ))
                        ->render('product');
        
        $this->_adata['aSort'] = $this->product->getSort();
    }
    
    public function ajax_save() {
        $apost = $this->input->post('product');   
        $this->load->library('form_validation', null, 'validation');
        $this->validation->set_rules($this->product->get_rule());
        $this->validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->validation->run() === false) {
            $this->return_fail_json($this->product->get_validation_error());
            return false;
        }
        
        if ((bool)$apost) {
            $this->product->set(array(
                'id'   => $apost['id'],
                'name' => $apost['name'],
                'summary' => $apost['summary'],
                'description' => $apost['description'],
                'image' => $apost['image'],
                'source' => $apost['source'],
                'level_id'   => $apost['level'],
                'order' => $apost['order'],
                'is_actived' => $apost['is_actived'],
                'is_featured' => $apost['is_featured'],
                'language_id' => $apost['language'],
                'meta_title' => $apost['meta_title'],
                'meta_keyword' => $apost['meta_keyword'],
                'meta_description' => $apost['meta_description'],
                'meta_robot' => $apost['meta_robot'],
                'atag'   => $apost['tag']
            ));
            //Save and edit in this.
            $svar_message = "phrase var='product.add_new_product_successfully'";
            
            if($apost['id']){
                $svar_message = "phrase var='product.edit_product_successfully'";
            }
            
            //Get current page. Use when reload page current after edit.
            $icur_page = $apost['cur_page'];
            
            if ((bool) $areturn = $this->product->save1()) {
                $areturn['cur_page'] = $icur_page;
                $this->return_success_json($areturn, $this->lang->line($svar_message));
                return true;
            }
        }
    }
    
    public function add() {
        if (!(bool) $this->input->is_ajax_request()) {
           $this->_redirect_index();
        }

        $aConfig = $this->_getRuleProduct();
        $this->load->library('form_validation', null, 'validation');
        $this->validation->set_rules($aConfig);
        $this->validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->validation->run() === false) {
            $this->return_fail_json($this->_getValidationError());
            return false;
        }

        if ((bool) $aProduct = $this->input->post('product')) {
            if ((bool) $aProduct = $this->product->add($aProduct)) {
                $this->return_success_json($aProduct, $this->lang->line("phrase var='product.add_new_product_successfully'"));
                return true;
            }
        }

        return false;
    }
    
    public function edit() {
        if (!(bool) $this->input->is_ajax_request()) {
            redirect('product/admincp/index');
            return false;
        }

        $aConfig = $this->_getRuleProduct();
        $this->load->library('form_validation', null, 'validation');
        $this->validation->set_rules($aConfig);
        $this->validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->validation->run() === false) {
            $this->return_fail_json($this->_getValidationError());

            return false;
        }

        if ((bool) $aProduct = $this->input->post('product')) {
            //Get current page. Use when reload page current after edit.
            $iCurPage = $aProduct['cur_page'];
//            $iCurPage = $aProduct['cur_page'];
            if ((bool) $aProduct = $this->product->edit($aProduct)) {
                $aProduct['cur_page'] = $iCurPage;
                $this->return_success_json($aProduct, $this->lang->line("phrase var='product.edit_product_successfully'"));
                return true;
            }
        }

        return false;
    }

    public function uploadImage() {
        $aConfig = array(
            'encrypt_name' => true,
            'upload_path' => APPPATH . 'static/images/product/',
            'allowed_types' => 'jpeg|jpg|png|bmp',
        );

        $this->load->library('upload', $aConfig);

        if ($this->upload->do_upload('product_image')) {
            if ((bool) $aData = $this->upload->data()) {
                $aImage = $this->product->addImage($aData['file_name']);
                $aConfigImage = array(
                    'source_image' => APPPATH . 'static/images/product/' . $aData['file_name'],
                    //'create_thumb' => TRUE,
                    'maintain_ratio' => TRUE,
                    'width' => 150,
                    'height' => 150,
                    'new_image' => APPPATH . 'static/images/product/thumb/' . $aData['file_name']
                );

                $this->load->library('image_lib', $aConfigImage);

                if ($this->image_lib->resize()) {
                    ///Create obsolute_path_new_image to get link to file image for showing after finish upload
                    //Reason: relative path image, when append image, it not show.
                    $aData += array('obsolute_path_new_image' => base_url() . '/' . $aConfigImage['new_image']);
                    return $this->return_success_json($aConfigImage + $aData, '');
                }

                return $this->return_fail_json($config, $this->image_lib->display_errors('<div class="error">', '</div>'));
            }
        }

        return $this->return_fail_json($aConfig, $this->upload->display_errors('<div class="error">', '</div>'));
    }

    public function ajax_get_list($offset = null) {
        $offset = !empty($offset) ? $offset : 1;
        $aSearch = $this->input->post('search');
        $aProduct = $this->product->getListAdmin($offset, $aSearch);

        //Get list of page.
        $aPage = $this->product->get_pager('product/admincp/index/ajax_get_list');
        $aPage = $this->product->get_pager_admin($aPage);

        $aReturn = array(
            'list' => $aProduct,
            'pages'    => $aPage
        );

        $this->return_success_json($aReturn, '');
    }

    public function delete() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $aIds = $this->input->post('product_ids');
        $iCurPage = $this->input->post('cur_page');
        $aIds = (array) json_decode($aIds);

        if ((bool) $this->product->delete($aIds)) {
            $aResult = $this->product->getListAdmin((int) $iCurPage);
            //Prepare in case if delete all items in a page.
            if (!empty($aResult)) {
                $this->return_success_json(array('page' => $iCurPage), '');
            } else {
                $this->return_success_json(array('page' => $iCurPage - 1), '');
            }
            return true;
        }

        $this->return_fail_json(NULL, '');
    }

    public function get() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $iId = $this->input->post('product_id');
        if ((bool) $aproduct = $this->product->getById($iId, false)) {
            $this->return_success_json($aproduct, '');

            return true;
        }

        $this->return_fail_json(NULL, '');
    }

    public function sort() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $aColum = $this->input->post('column');
        $sTypeSort = $this->product->sort($aColum);
        $this->return_success_json(array('type_sort' => $sTypeSort), '');
    }

    public function ajax_set_view() {
        $iNumView = $this->input->post('num_view');

        if ($iNumView) {
            $this->session->set_userdata($this->config->item('ele_per_page'), $iNumView);
            $this->return_success_json(array('num_view' => $iNumView), '');

            return true;
        }

        $this->return_fail_json(array('num_view' => $iNumView), '');
    }

    public function getSort() {
        $this->_sort = $this->session->userdata($this->config->item('sort'));

        if (!(bool) $this->_sort) {
            return array('order' => 'asc');
        }
    }

    private function _load() {
        $this->load->library('pagination');
        $this->load->helper(array('url', 'form'));
        $this->load->model(array('user', 'product'));
        $this->lang->load('admin/general', $this->_slang_name);
        $this->lang->load('admin/product', $this->_slang_name);
    }
}
?>